//
//  NetWorkTools.swift
//  MicroBlog
//
//  Created by Jokin on 2017/3/29.
//  Copyright © 2017年 jokin. All rights reserved.
//

import UIKit
import AFNetworking


enum RequestType: Int {
    case get = 0
    case post = 1
}

class NetWorkTools: AFHTTPSessionManager {
    
    static let sharedTools: NetWorkTools = {
        let tools = NetWorkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        
    }()
    
    
    func requestFirstLodIn(type: RequestType, urlStr: String, params: Any?, finishClaaBlock:@escaping (Any? , Error?) ->()) {
        
        if type == .get {
            get(urlStr, parameters: params, progress: nil, success: { (_, responce) in
                finishClaaBlock(responce,nil)
                
            }, failure: { (_, error) in
                finishClaaBlock(nil,error)
            })
        }else {
            
            post(urlStr, parameters: params, progress: nil, success: { (_, responce) in
                finishClaaBlock(responce, nil)
            }, failure: { (_, error) in
                finishClaaBlock(nil, error)
            })
            
            
        }
        
        
        
    }
    
    // 根据code获取accesstoken
    func requestAccessToken(code: String, finishCallBack:@escaping (Any?, Error?) ->()) {
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        let parame = ["client_id" : AppKey,
                      "client_secret" : AppSearet,
                      "grant_type" : "authorization_code",
                      "code" : code,
                      "redirect_uri" : ComeBackUrl]
        requestFirstLodIn(type: .post, urlStr: urlStr, params: parame, finishClaaBlock: finishCallBack)
        
        
        
        
    }
    
    func requestUserInfo(token: String, uid: Int64, finshBlack: @escaping (Any?, Error?) ->()) {
        
        let urlStr = "https://api.weibo.com/2/users/show.json"

        let parame : [String : Any] = [
            "access_token": token,
            "uid": uid
        ]
        requestFirstLodIn(type: .get, urlStr: urlStr, params: parame, finishClaaBlock:finshBlack)
        
    }
    
    

}
